package cn.bugstack.domain.activity.service.discount;

import cn.bugstack.domain.activity.adapter.repository.IActivityRepository;
import cn.bugstack.domain.activity.model.valobj.DiscountTypeEnum;
import cn.bugstack.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
public abstract class AbstractDiscountCalculateService implements IDiscountCalculateService {

    @Resource
    protected IActivityRepository repository;


    @Override
    public BigDecimal calculate(String userId, BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount) {
        //  1. 人群标签过滤
        if(DiscountTypeEnum.TAG.equals(groupBuyDiscount.getDiscountType())){
            boolean isCrowdRange = filterTagId(userId, groupBuyDiscount.getTagId());
            if(!isCrowdRange) {
                log.info("折扣优惠计算拦截 - userID:{}", userId);
                return originalPrice;
            }
        }
        //  2.折扣优惠计算
        return docalculate(originalPrice, groupBuyDiscount);
    }

    // 人群过滤函数，限定人群才有优惠
    private boolean filterTagId(String userId, String tagId){
        return repository.isTagCrowdRange(tagId, userId);
    }

    protected abstract BigDecimal docalculate(BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount);

    protected BigDecimal filterZero(BigDecimal Price){
        if(Price.compareTo(BigDecimal.ZERO) <= 0){
            return new BigDecimal("0.01");
        }
        return Price;
    };

}
